package com.qianxx.viewlibrary.menu.appdock;

import android.content.Context;
import android.graphics.Camera;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Transformation;
import android.widget.Gallery;

@SuppressWarnings("deprecation")
public class AppDock extends Gallery {

	private Camera mCamera = new Camera();

	public AppDock(Context context) {
		super(context);
		this.setStaticTransformationsEnabled(true);
	}

	public AppDock(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.setStaticTransformationsEnabled(true);
	}

	public AppDock(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		this.setStaticTransformationsEnabled(true);
	}

	/**
	 * 当Gallery滑动时会执行该方法,因此重写该方法来实现View位置的变化.
	 * 在重写该方法前必须setStaticTransformationsEnabled(true)
	 */
	@Override
	protected boolean getChildStaticTransformation(View child, Transformation t) {
		int mCoveflowCenter = getCenterOfCoverflow();
		int childCenter = getCenterOfView(child);
		t.clear();
		t.setTransformationType(Transformation.TYPE_MATRIX);
		int rotationAngle = (mCoveflowCenter - childCenter) * 5 / 18;
		transformImageBitmap((View) child, t, rotationAngle);
		// 移动好当前View的位置后记得要重新绘制所有的child View
		invalidateChilds();
		return true;
	}

	/**
	 * 获得Gallery中点的水平位置
	 *
	 * @return
	 */
	private int getCenterOfCoverflow() {
		return (getWidth() - getPaddingLeft() - getPaddingRight()) / 2
				+ getPaddingLeft();
	}

	/**
	 * 获得当前View的中点水平位置
	 *
	 * @param view
	 * @return
	 */
	private static int getCenterOfView(View view) {
		return view.getLeft() + view.getWidth() / 2;
	}

	/**
	 * 重绘每个child
	 *
	 * @return
	 */
	private void invalidateChilds() {
		for (int i = getChildCount() - 1; i >= 0; i--) {
			getChildAt(i).invalidate();
		}
	}

	/**
	 * 移动当前View位置
	 *
	 * @param child
	 * @param t
	 * @param y
	 */
	private void transformImageBitmap(View child, Transformation t, int y) {
		mCamera.save();
		final Matrix imageMatrix = t.getMatrix();
		final int imageHeight = child.getLayoutParams().height;
		final int imageWidth = child.getLayoutParams().width;
		final int height = Math.abs(y);
		// 将当前View向y轴移动height
		mCamera.translate(0.0f, height - getHeight() / 3, 0.0f);
		mCamera.getMatrix(imageMatrix);
		imageMatrix.preTranslate(-(imageWidth / 2), -(imageHeight / 2));
		imageMatrix.postTranslate((imageWidth / 2), (imageHeight / 2));
		mCamera.restore();
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
						   float velocityY) {
		// 设置滑动速率
		// return super.onFling(e1, e2, velocityX/1.5f, velocityY);
		return true;
	}

}
